﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using UpdateApp.Properties;
using TopVidionApplication;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace UpdateApp
{
    public partial class Windows_Update : VideoStream.Windows.WindowsBase
    {
        //public static int VersionCode = -1;
        //public static string VersionPath
        //{
        //    get
        //    {
        //        return "http://122.112.226.39:8082/topvision-api/app/sysversion/getNewestVersion";
        //    }
        //}
        //// http://122.112.226.39:8082/topvision-api/app/sysversion/getNewestVersion 
        //// http://topvision-cv.com/TopVisionWeb/app/sysversion?packageNameSch=com.topvision.videostreambackstage.pc&platformSch=1

        //public static string platform = "1";    //0 阿里 //1 华为
        //public const string packageName = "com.topvision.remotesupport.meetingvideoplay";
        //public string urlFormat = "{0}?packageName={1}&platform={2}";
        //public static AppVersion AppVersionConfig;


        //public string newVersionFormatString = "发现新版本：{0}";

        //public bool CanUpdate = false;


        public Windows_Update()
        {
            InitializeComponent();
            InitUI();
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            InitEvent();
            UpdateUI();
            CheckVersion();
        }
        public override void InitUI()
        {
            base.InitUI();
        }
        public override void InitEvent()
        {
            base.InitEvent();

            btn_Update.Click += Btn_Update_Click;
            btn_Min.Click += (o, e) => { this.WindowState = FormWindowState.Minimized; };
            btn_Close.Click += (o, e) =>
            {
                //var ret = MessageBox.Show(this, "", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                Close();
                Application.Exit();
            };

        }

        public override void UpdateUI()
        {
            base.UpdateUI();

            btn_Update.Enabled = false;
            lab_UpdateInfo.Text = "";
            icon_UpdateVersion._Text = "";
            btn_Update._Text = "立即更新";
            bar_Download.Hide();
        }


        public void CheckVersion()
        {
            var ret = UpdateTool.Check();
            switch (ret)
            {
                case 0:
                    Unwanted();
                    break;
                case 1:
                    Optional();
                    break;
                case 2:
                    Necessary();
                    break;
                default:
                    break;
            }
        }

        private void Unwanted()
        {
            icon_UpdateVersion._Text = "已是最新版本";
        }

        private void Optional()
        {
            icon_UpdateVersion._Text = "发现新版本：" + UpdateTool.AppVersionConfig.versionname;
            lab_UpdateInfo.Text = UpdateTool.AppVersionConfig.content;
            btn_Update.Show();
            btn_Update.Enabled = true;
        }

        private void Necessary()
        {
            Optional();
            icon_UpdateVersion._Text = "(*)发现新版本：" + UpdateTool.AppVersionConfig.versionname;
        }

        private void ShowVersionMessage(string versionNb, string message)
        {
            icon_UpdateVersion._Text = versionNb;
            lab_UpdateInfo.Text = message;
        }

        private void SetUpdateUI()
        {
            btn_Update._Text = "立即更新";
        }

        private void DoUpdate()
        {

            DownloadFile();

        }

        private void DownloadFile()
        {
            string url = UpdateTool.AppVersionConfig.loadurl;

            btn_Update.Hide();
            bar_Download.Show();

            HttpAPI.DownloadDataProgressChanged += (o, e) =>
            {
                bar_Download.Value = e.ProgressPercentage;
            };
            HttpAPI.DownloadDataCompleted += (o, e) =>
            {
                Install(e);
            };
            HttpAPI.GetAsync(new Uri(url), HttpRequestHeader.Accept, HttpRequestHeaderValue.None);
        }

        private async void Install(DownloadDataCompletedEventArgs e)
        {
            string file = Path.Combine(Application.StartupPath, UpdateTool.AppVersionConfig.versionname + ".exe");
            File.WriteAllBytes(file, e.Result);
            await Task.Delay(2000);
            if (VideoStreamCheck())
            {
                await Task.Delay(1000);
                RunAppAsync(file);
            }
        }

        private void RunAppAsync(string appName)
        {
            try
            {
                Process.Start(appName);
            }
            catch (Exception ex)
            {
                //ApplicationLog.Write("更新错误：" + ex.Message, AppLogType.错误);

                MessageBox.Show("安装失败，请检测安装包", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Close();
            }
        }


        private void Btn_Update_Click(object sender, EventArgs e)
        {
            DoUpdate();
        }

        public static bool VideoStreamCheck()
        {
            List<Process> pro = Process.GetProcessesByName("VideoStream").ToList();
            if (pro.Count > 0)
            {
                var ret = MessageBox.Show("继续更新将会关闭已打开的程序。", "更新", MessageBoxButtons.OKCancel);
                if (ret == DialogResult.OK)
                {
                    pro.ForEach(o => o.Kill());
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return true;
            }
        }


        public static bool ProcessCheck()
        {
            bool ok = true;
            try
            {
                Process curProcess = Process.GetCurrentProcess();
                List<Process> pro = Process.GetProcessesByName(curProcess.ProcessName.Replace(".vshost", "")).Where(o => o.Id != curProcess.Id).ToList();
                if (pro.Count > 0)
                {
                    pro.ForEach(o =>
                    {
                        SendMessage(o.MainWindowHandle, 274, 61440 + 32, 0);
                        SendMessage(o.MainWindowHandle, 274, 61440 + 288, 0);
                    });

                    ok = false;
                }
            }
            catch (Exception ex)
            {
                ok = false;
            }

            return ok;
        }


        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

    }




    #region 程序更新 版本类型

    public class VersionRoot
    {
        ///// <summary>
        ///// 
        ///// </summary>
        //public int currentPageIndex { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int firstPageIndex { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int lastPageIndex { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int nextPageIndex { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int pageCount { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int pageIndex { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int pageSize { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int prePageIndex { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public List<AppVersion> rows { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int start { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int total { get; set; }
        /// <summary>
        /// 请求数据成功!
        /// </summary>
        public string msg { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int code { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public AppVersion data { get; set; }
    }

    public class AppVersion
    {
        ///// </summary>
        //public string content { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public string createdTime { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public string editedTime { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int id { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public string isDeleted { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public string loadUrl { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int must { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int operaterId { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public string packageName { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public string platform { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public int sortId { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public string versionCode { get; set; }
        ///// <summary>
        ///// 
        ///// </summary>
        //public string versionName { get; set; }

        /// <summary>
        /// 当前测试内容，请不要更新
        /// </summary>
        public string content { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string createTime { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string createdtime { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string creater { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string disabled { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string editedtime { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int id { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string isdeleted { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string loadurl { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string modifier { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string modifyTime { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int must { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string operaterid { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string packagename { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string platform { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string remark { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string sortid { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string version { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string versioncode { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string versionname { get; set; }
    }

    #endregion

}
